export default {
    bind(el, binding) {
        const handle = el.querySelector(binding.value.handle) || el;
        el.style.position = 'absolute'; // 确保元素可以自由移动

        handle.addEventListener('mousedown', function (e) {
            const disX = e.clientX - el.offsetLeft;
            const disY = e.clientY - el.offsetTop;

            function onMouseMove(e) {
                let newX = e.clientX - disX;
                let newY = e.clientY - disY;

                // 添加边界检查
                const viewportWidth = window.innerWidth;
                const viewportHeight = window.innerHeight;
                const elWidth = el.offsetWidth;
                const elHeight = el.offsetHeight;

                // 限制元素不被拖出视口
                newX = Math.max(0, Math.min(newX, viewportWidth - elWidth));
                newY = Math.max(0, Math.min(newY, viewportHeight - elHeight));

                el.style.left = newX + 'px';
                el.style.top = newY + 'px';
            }

            function onMouseUp() {
                document.removeEventListener('mousemove', onMouseMove);
                document.removeEventListener('mouseup', onMouseUp);
            }

            document.addEventListener('mousemove', onMouseMove);
            document.addEventListener('mouseup', onMouseUp);

            e.preventDefault(); // 阻止默认行为，如拖动图片等
        });

        handle.addEventListener('mouseenter', function () {
            handle.style.cursor = 'move';
        });

        handle.addEventListener('mouseleave', function () {
            handle.style.cursor = '';
        });
    }
};
